
import 'dart:convert';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart';
import 'package:flutter/foundation.dart';



_parseAndDecode(String response) {
  return jsonDecode(response);
}

parseJson(String text) {
  return compute(_parseAndDecode, text); //新起一个线程用来数据解析
}
abstract class BaseHttp extends DioForNative {
     BaseHttp(){
       //抓包配置（具体自行百度dio）
//       (httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
//               // config the http client
//               client.findProxy = (uri) {
//               //proxy all request to localhost:8888
//               return "PROXY localhost:8888";
//            };
//            // you can also create a HttpClient to dio
//           // return HttpClient();

       (transformer as DefaultTransformer).jsonDecodeCallback = parseJson;
        interceptors..add(HeaderInterceptor());
        init();
       }
       //子类需要重写
       void  init(){
           //添加自己的自定义初始化逻辑
       }
}

class HeaderInterceptor extends InterceptorsWrapper{
    @override
   onRequest(RequestOptions options) async{
       //自定义请求头
//      options.headers['version'] = "3.1.2";
//      options.headers['platform'] = "IOS";
    return options;
  }
}

//自定义基类（根据后端返回格式自定义）
abstract class  BaseResponseData{
     int state  = 0;  //后端返回的状态码
     String msg;   //消息
     dynamic data;  //数据
     bool get sucess;
     BaseResponseData({this.state,this.msg,this.data});
     @override
     String toString() {
       return 'BaseRespData{state: $state, msg: $msg, data: $data}';
     }
}

//根据后端自定义的Exception
class NotSuccessException implements Exception {
     String message;
     NotSuccessException.fromResponData(BaseResponseData responseData){
        message  = responseData.msg;
     }

     @override
     String toString() {
       return 'NotExpectedException{respData: $message}';
     }
}

//再举一例（比如登录权限不够，需要跳转授权页面）
class UnAuthorizedException implements Exception {
     const UnAuthorizedException();
     @override
     String toString() => 'UnAuthorizedException';
}


